package com.ninong.ker.admin.service.impl;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ninong.ker.admin.domain.Dept;
import com.ninong.ker.admin.mapper.DeptMapper;
import com.ninong.ker.admin.rest.vo.DeptVO;
import com.ninong.ker.admin.service.DeptService;
import com.ninong.ker.common.exception.CmdException;
import com.ninong.ker.common.tools.Constants;
import com.ninong.ker.common.tools.enums.BusinessEnum;

/**
 * 
 * @author cmd
 *
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

	private static final String PARENT = "0";

	@Override
	public List<DeptVO> listDeptTree(Dept dto) {
		dto.setPid(PARENT);
		return baseMapper.selectDeptTree(dto);
	}

	@Override
	public void delete(String[] ids) {
		baseMapper.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public void create(Dept entity) {
		Integer count = null;
		if (StringUtils.isEmpty(entity.getId())) {
			count = baseMapper.selectCount(new QueryWrapper<Dept>().eq("name", entity.getName()));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DEPT_NAME_REPEAT);
			}
			count = baseMapper.selectCount(new QueryWrapper<Dept>().eq("code", entity.getCode()));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DEPT_CODE_REPEAT);
			}
		} else {
			count = baseMapper
					.selectCount(new QueryWrapper<Dept>().ne("id", entity.getId()).eq("name", entity.getName()));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DEPT_NAME_REPEAT);
			}
			count = baseMapper
					.selectCount(new QueryWrapper<Dept>().ne("id", entity.getId()).eq("code", entity.getCode()));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DEPT_CODE_REPEAT);
			}

		}
		saveOrUpdate(entity);
	}

	@Override
	public Dept get(String id) {
		Dept entity = baseMapper.selectById(id);
		if (ObjectUtils.isEmpty(entity)) {
			entity = new Dept();
		}
		Dept dto = new Dept();
		dto.setPid(PARENT);
		entity.setResouces(baseMapper.selectDeptTree(dto));
		return entity;
	}
}
